"use client"

import { useState, useEffect } from "react"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { SmilePlus, Heart, ReplyIcon, RefreshCw, ChevronDown, ChevronUp, MapPin, AtSign, Trash2 } from "lucide-react"
import { EmojiPicker } from "@/components/comments/shared/emoji-picker"
import { toast } from "@/components/ui/use-toast"
import { cn } from "@/lib/utils"
import {
  fetchComments,
  fetchReplies,
  postComment,
  postReply,
  toggleFavorite,
  deleteComment,
  deleteReply,
} from "@/lib/api-client"
import type { Comment, CommentResponse, ReplyResponse } from "@/types/comment"
import Link from "next/link"
import { useAuth } from "@/contexts/auth-context"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"

interface CommentSectionProps {
  contentId: string
  contentType: "album" | "playlist" | "community" | "mv"
}

export default function CommentSection({ contentId, contentType }: CommentSectionProps) {
  const { isAuthenticated, user } = useAuth()
  const [commentText, setCommentText] = useState("")
  const [replyText, setReplyText] = useState("")
  const [replyingTo, setReplyingTo] = useState<{
    commentId: number // 主评论ID
    replyId?: number // 回复ID（如果回复的是回复）
    username: string // 被回复用户名
  } | null>(null)
  const [showEmojiPicker, setShowEmojiPicker] = useState(false)
  const [comments, setComments] = useState<Comment[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [isLoadingMore, setIsLoadingMore] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [totalComments, setTotalComments] = useState(0)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageLimit, setPageLimit] = useState(10)
  const [expandedComments, setExpandedComments] = useState<Record<number, boolean>>({})
  const [loadingReplies, setLoadingReplies] = useState<Record<number, boolean>>({})
  const [replyPages, setReplyPages] = useState<Record<number, { page: number; limit: number; total: number }>>({})

  // 删除确认对话框状态
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [deleteTarget, setDeleteTarget] = useState<{
    type: "comment" | "reply"
    commentId: number
    replyId?: number
  } | null>(null)
  const [isDeleting, setIsDeleting] = useState(false)

  // 获取当前登录用户名
  const currentUsername = user?.username || localStorage.getItem("username")

  // 计算是否有更多评论
  const hasMoreComments = () => {
    return currentPage * pageLimit < totalComments
  }

  // 计算下一页页码
  const getNextPage = () => {
    return currentPage + 1
  }

  // 计算评论是否有更多回复
  const hasMoreReplies = (commentId: number) => {
    const replyPage = replyPages[commentId]
    if (!replyPage) return false
    return replyPage.page * replyPage.limit < replyPage.total
  }

  // 获取回复的下一页页码
  const getNextReplyPage = (commentId: number) => {
    const replyPage = replyPages[commentId]
    if (!replyPage) return 1
    return replyPage.page + 1
  }

  const loadComments = async (page = 1, append = false) => {
    try {
      if (page === 1) {
        setIsLoading(true)
      } else {
        setIsLoadingMore(true)
      }

      const response: CommentResponse = await fetchComments({
        contentId,
        contentType,
        page,
        limit: pageLimit,
      })

      setTotalComments(response.total)
      setCurrentPage(response.page)
      setPageLimit(response.limit)

      if (append) {
        setComments((prev) => [...prev, ...response.items])
      } else {
        setComments(response.items || [])
      }
    } catch (error) {
      console.error("Failed to fetch comments:", error)
      toast({
        title: "获取评论失败",
        description: "请稍后重试",
      })
    } finally {
      setIsLoading(false)
      setIsLoadingMore(false)
    }
  }

  const loadReplies = async (commentId: number, page = 1, append = false) => {
    try {
      setLoadingReplies((prev) => ({ ...prev, [commentId]: true }))

      const response: ReplyResponse = await fetchReplies({
        commentId: commentId.toString(),
        page,
        limit: 5,
      })

      // 更新回复分页信息
      setReplyPages((prev) => ({
        ...prev,
        [commentId]: {
          page: response.page,
          limit: response.limit,
          total: response.total,
        },
      }))

      setComments((prev) =>
          prev.map((comment) => {
            if (comment.id === commentId) {
              return {
                ...comment,
                replies: append ? [...(comment.replies || []), ...response.items] : response.items,
              }
            }
            return comment
          }),
      )
    } catch (error) {
      console.error("Failed to fetch replies:", error)
      toast({
        title: "获取回复失败",
        description: "请稍后重试",
      })
    } finally {
      setLoadingReplies((prev) => ({ ...prev, [commentId]: false }))
    }
  }

  const toggleReplies = async (commentId: number) => {
    const isExpanded = expandedComments[commentId]

    if (isExpanded) {
      // 收起回复
      setExpandedComments((prev) => ({ ...prev, [commentId]: false }))
    } else {
      // 展开回复，如果还没加载过回复，则加载
      setExpandedComments((prev) => ({ ...prev, [commentId]: true }))
      const comment = comments.find((c) => c.id === commentId)
      if (!comment.replies) {
        await loadReplies(commentId)
      }
    }
  }

  const loadMoreReplies = async (commentId: number) => {
    const nextPage = getNextReplyPage(commentId)
    await loadReplies(commentId, nextPage, true)
  }

  useEffect(() => {
    loadComments()
  }, [contentId, contentType])

  const handleComment = async () => {
    if (!commentText.trim()) return
    const userId = Number.parseInt(localStorage.getItem("userId") as string)

    try {
      setIsSubmitting(true)

      const response = await postComment({
        userId: userId,
        contentId: Number.parseInt(contentId),
        contentType: contentType,
        content: commentText,
      })

      if (response.code === 200) {
        setComments([response.data, ...comments])
        setCommentText("")
        setShowEmojiPicker(false)
        toast({
          title: "评论成功",
          description: "你的评论已发布",
        })
      }
    } catch (error) {
      console.error("Failed to post comment:", error)
      toast({
        title: "评论失败",
        description: "请稍后重试",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleReply = async () => {
    if (!replyText.trim() || !replyingTo) return

    try {
      setIsSubmitting(true)

      // 构建回复数据
      const replyData = {
        contentId,
        contentType,
        content: replyText,
        parentId: replyingTo.commentId,
        // 如果回复的是回复，则传递被回复的用户名
        replyToId: replyingTo.replyId,
        replyToUsername: replyingTo.replyId ? replyingTo.username : undefined,
      }

      const response = await postReply(replyData)

      if (response.code === 200) {
        // 确保回复区域已展开
        setExpandedComments((prev) => ({ ...prev, [replyingTo.commentId]: true }))

        // 更新评论列表
        setComments(
            comments.map((comment) =>
                comment.id === replyingTo.commentId
                    ? {
                      ...comment,
                      replyCount: comment.replyCount + 1,
                      replies: comment.replies ? [response.data, ...comment.replies] : [response.data],
                    }
                    : comment,
            ),
        )

        // 更新回复分页信息
        if (replyPages[replyingTo.commentId]) {
          setReplyPages((prev) => ({
            ...prev,
            [replyingTo.commentId]: {
              ...prev[replyingTo.commentId],
              total: prev[replyingTo.commentId].total + 1,
            },
          }))
        }

        setReplyText("")
        setReplyingTo(null)
        setShowEmojiPicker(false)

        toast({
          title: "回复成功",
          description: "你的回复已发布",
        })
      }
    } catch (error) {
      console.error("Failed to post reply:", error)
      toast({
        title: "回复失败",
        description: "请稍后重试",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleLike = async (commentId: number, isLiked: boolean) => {
    if (!isAuthenticated) {
      toast({
        title: "请先登录",
        description: "登录后即可点赞评论",
      })
      return
    }

    try {
      // 乐观更新 UI
      setComments(
          comments.map((comment) => {
            // 如果是主评论
            if (comment.id === commentId) {
              return {
                ...comment,
                likeCount: isLiked ? comment.likeCount - 1 : comment.likeCount + 1,
                isLiked: !isLiked,
              }
            }

            // 如果是回复中的评论
            if (comment.replies) {
              return {
                ...comment,
                replies: comment.replies.map((reply) =>
                    reply.id === commentId
                        ? {
                          ...reply,
                          likes: isLiked ? reply.likes - 1 : reply.likes + 1,
                          isLiked: !isLiked,
                        }
                        : reply,
                ),
              }
            }

            return comment
          }),
      )

      const userId = localStorage.getItem("userId")
      if (userId) {
        // 使用通用的 toggleFavorite 函数
        await toggleFavorite({
          action: isLiked,
          contentId: commentId.toString(),
          contentType: "comment",
          userId: +userId,
        })
      }
    } catch (error) {
      console.error("点赞、取消点赞评论失败:", error)
      toast({
        title: "操作失败",
        description: "请稍后重试",
      })
    }
  }

  // 打开删除确认对话框
  const confirmDelete = (type: "comment" | "reply", commentId: number, replyId?: number) => {
    setDeleteTarget({ type, commentId, replyId })
    setShowDeleteDialog(true)
  }

  // 执行删除操作
  const handleDelete = async () => {
    if (!deleteTarget) return

    try {
      setIsDeleting(true)

      if (deleteTarget.type === "comment") {
        // 删除主评论
        await deleteComment(deleteTarget.commentId)

        // 更新评论列表
        setComments(comments.filter((comment) => comment.id !== deleteTarget.commentId))
        setTotalComments((prev) => prev - 1)

        toast({
          title: "删除成功",
          description: "评论已删除",
        })
      } else {
        // 删除回复
        await deleteReply(deleteTarget.commentId, deleteTarget.replyId!)

        // 更新评论列表
        setComments(
            comments.map((comment) => {
              if (comment.id === deleteTarget.commentId) {
                return {
                  ...comment,
                  replyCount: comment.replyCount - 1,
                  replies: comment.replies?.filter((reply) => reply.id !== deleteTarget.replyId),
                }
              }
              return comment
            }),
        )

        // 更新回复分页信息
        if (replyPages[deleteTarget.commentId]) {
          setReplyPages((prev) => ({
            ...prev,
            [deleteTarget.commentId]: {
              ...prev[deleteTarget.commentId],
              total: prev[deleteTarget.commentId].total - 1,
            },
          }))
        }

        toast({
          title: "删除成功",
          description: "回复已删除",
        })
      }
    } catch (error) {
      console.error("删除评论失败:", error)
      toast({
        title: "删除失败",
        description: "请稍后重试",
      })
    } finally {
      setIsDeleting(false)
      setShowDeleteDialog(false)
      setDeleteTarget(null)
    }
  }

  const addEmoji = (emoji: string) => {
    if (replyingTo) {
      setReplyText(replyText + emoji)
    } else {
      setCommentText(commentText + emoji)
    }
  }

  // 检查评论是否属于当前用户
  const isCommentOwner = (username: string) => {
    return currentUsername === username
  }

  return (
      <div className="space-y-8">
        {/* 评论总数 */}
        <div className="flex justify-between items-center">
          <h3 className="text-lg font-medium">{totalComments}条评论</h3>
          <Button variant="ghost" size="sm" onClick={() => loadComments(1)} disabled={isLoading}>
            <RefreshCw className={cn("h-4 w-4 mr-1", isLoading && "animate-spin")} />
            刷新
          </Button>
        </div>

        {/* 评论输入框 */}
        {isAuthenticated ? (
            <div className="space-y-4">
              <div className="relative">
                <Textarea
                    placeholder={
                      replyingTo
                          ? replyingTo.replyId
                              ? `回复 ${replyingTo.username}...`
                              : "说说你的看法吧"
                          : "说说你的看法吧"
                    }
                    value={replyingTo ? replyText : commentText}
                    onChange={(e) => (replyingTo ? setReplyText(e.target.value) : setCommentText(e.target.value))}
                    className="min-h-[100px] pr-20"
                    maxLength={300}
                    disabled={isSubmitting}
                />
                {replyingTo && replyingTo.replyId && (
                    <div className="absolute top-2 left-2 text-sm text-blue-500 flex items-center">
                      <AtSign className="h-3 w-3 mr-1" />
                      {replyingTo.username}
                    </div>
                )}
                <div className="absolute bottom-2 right-2 text-sm text-muted-foreground">
                  剩余{300 - (replyingTo ? replyText.length : commentText.length)}字
                </div>
              </div>
              <div className="flex justify-between items-center">
                <div className="flex items-center gap-2">
                  <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => setShowEmojiPicker(!showEmojiPicker)}
                      disabled={isSubmitting}
                  >
                    <SmilePlus className="h-5 w-5" />
                  </Button>
                </div>
                <div className="flex items-center gap-2">
                  {replyingTo && (
                      <Button variant="outline" onClick={() => setReplyingTo(null)} disabled={isSubmitting}>
                        取消回复
                      </Button>
                  )}
                  <Button onClick={replyingTo ? handleReply : handleComment} disabled={isSubmitting}>
                    {isSubmitting ? "提交中..." : replyingTo ? "回复" : "发表评论"}
                  </Button>
                </div>
              </div>
              {showEmojiPicker && <EmojiPicker onEmojiSelect={addEmoji} />}
            </div>
        ) : (
            <div className="text-center py-8 space-y-4">
              <p className="text-muted-foreground">登录后参与评论</p>
              <Link href="/login">
                <Button>登录</Button>
              </Link>
            </div>
        )}

        {/* 评论列表 */}
        <div className="space-y-6">
          {isLoading ? (
              <div className="flex justify-center py-8">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
              </div>
          ) : comments.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">暂无评论，快来发表第一条评论吧！</div>
          ) : (
              <>
                {comments.map((comment) => (
                    <div key={comment.id} className="space-y-4">
                      {/* 主评论 */}
                      <div className="flex gap-4">
                        <Avatar className="h-10 w-10">
                          <AvatarImage src={comment.avatar} />
                          <AvatarFallback>{comment.username[0]}</AvatarFallback>
                        </Avatar>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <span className="font-medium">{comment.username}</span>
                            {comment.isTop && <span className="text-xs bg-red-100 text-red-600 px-1 rounded">首评</span>}
                            <span className="text-sm text-muted-foreground">{comment.createdAt}</span>
                            {comment.location && (
                                <span className="text-sm text-muted-foreground flex items-center">
                          <MapPin className="h-3 w-3 mr-1" />
                                  {comment.location}
                        </span>
                            )}
                          </div>
                          <p className="text-sm whitespace-pre-line mb-2">{comment.content}</p>
                          <div className="flex items-center gap-4">
                            <Button
                                variant="ghost"
                                size="sm"
                                className={cn(comment.isLiked && "text-red-500")}
                                onClick={() => handleLike(comment.id, comment.isLiked)}
                            >
                              <Heart className={cn("h-4 w-4 mr-1", comment.isLiked && "fill-current")} />
                              {comment.likeCount > 0 && (
                                  <span className={cn(comment.likeCount >= 10000 ? "text-red-500" : "")}>
                            {comment.likeCount >= 10000
                                ? `${(comment.likeCount / 10000).toFixed(1)}万`
                                : comment.likeCount}
                          </span>
                              )}
                            </Button>
                            {isAuthenticated && (
                                <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() =>
                                        setReplyingTo({
                                          commentId: comment.id,
                                          username: comment.username,
                                        })
                                    }
                                >
                                  <ReplyIcon className="h-4 w-4 mr-1" />
                                  回复
                                </Button>
                            )}
                            {isAuthenticated && isCommentOwner(comment.username) && (
                                <Button
                                    variant="ghost"
                                    size="sm"
                                    className="text-red-500"
                                    onClick={() => confirmDelete("comment", comment.id)}
                                >
                                  <Trash2 className="h-4 w-4 mr-1" />
                                  删除
                                </Button>
                            )}
                          </div>
                        </div>
                      </div>

                      {/* 回复区域 */}
                      {comment.replyCount > 0 && (
                          <div className="ml-14">
                            {/* 展开/收起回复按钮 */}
                            <Button
                                variant="ghost"
                                size="sm"
                                className="mb-2 text-muted-foreground"
                                onClick={() => toggleReplies(comment.id)}
                                disabled={loadingReplies[comment.id]}
                            >
                              {loadingReplies[comment.id] ? (
                                  <RefreshCw className="h-4 w-4 mr-1 animate-spin" />
                              ) : expandedComments[comment.id] ? (
                                  <ChevronUp className="h-4 w-4 mr-1" />
                              ) : (
                                  <ChevronDown className="h-4 w-4 mr-1" />
                              )}
                              {expandedComments[comment.id] ? "收起" : `查看${comment.replyCount}条回复`}
                            </Button>

                            {/* 回复列表 */}
                            {expandedComments[comment.id] && comment.replies && (
                                <div className="space-y-4">
                                  {comment.replies.map((reply) => (
                                      <div key={reply.id} className="flex gap-4">
                                        <Avatar className="h-8 w-8">
                                          <AvatarImage src={reply.user.avatar} />
                                          <AvatarFallback>{reply.user.username[0]}</AvatarFallback>
                                        </Avatar>
                                        <div className="flex-1">
                                          <div className="flex items-center gap-2 mb-1">
                                            <span className="font-medium">{reply.user.username}</span>
                                            {reply.replyToUsername && (
                                                <>
                                                  <span className="text-muted-foreground">▶</span>
                                                  <span className="font-medium">{reply.replyToUsername}</span>
                                                </>
                                            )}
                                            <span className="text-sm text-muted-foreground">{reply.createdAt}</span>
                                          </div>
                                          <p className="text-sm whitespace-pre-line mb-2">{reply.content}</p>
                                          <div className="flex items-center gap-4">
                                            <Button
                                                variant="ghost"
                                                size="sm"
                                                className={cn(reply.isLiked && "text-red-500")}
                                                onClick={() => handleLike(reply.id, reply.isLiked)}
                                            >
                                              <Heart className={cn("h-4 w-4 mr-1", reply.isLiked && "fill-current")} />
                                              {reply.likes > 0 && (
                                                  <span className={cn(reply.likes >= 10000 ? "text-red-500" : "")}>
                                      {reply.likes >= 10000 ? `${(reply.likes / 10000).toFixed(1)}万` : reply.likes}
                                    </span>
                                              )}
                                            </Button>
                                            {isAuthenticated && (
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    onClick={() =>
                                                        setReplyingTo({
                                                          commentId: comment.id,
                                                          replyId: reply.id,
                                                          username: reply.user.username,
                                                        })
                                                    }
                                                >
                                                  <ReplyIcon className="h-4 w-4 mr-1" />
                                                  回复
                                                </Button>
                                            )}
                                            {isAuthenticated && isCommentOwner(reply.user.username) && (
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    className="text-red-500"
                                                    onClick={() => confirmDelete("reply", comment.id, reply.id)}
                                                >
                                                  <Trash2 className="h-4 w-4 mr-1" />
                                                  删除
                                                </Button>
                                            )}
                                          </div>
                                        </div>
                                      </div>
                                  ))}

                                  {/* 加载更多回复 */}
                                  {hasMoreReplies(comment.id) && (
                                      <Button
                                          variant="ghost"
                                          size="sm"
                                          className="ml-12 text-muted-foreground"
                                          onClick={() => loadMoreReplies(comment.id)}
                                          disabled={loadingReplies[comment.id]}
                                      >
                                        {loadingReplies[comment.id] ? (
                                            <RefreshCw className="h-4 w-4 mr-1 animate-spin" />
                                        ) : (
                                            <ChevronDown className="h-4 w-4 mr-1" />
                                        )}
                                        展开更多回复
                                      </Button>
                                  )}
                                </div>
                            )}
                          </div>
                      )}
                    </div>
                ))}

                {/* 加载更多评论 */}
                {hasMoreComments() && (
                    <div className="flex justify-center pt-4">
                      <Button variant="outline" onClick={() => loadComments(getNextPage(), true)} disabled={isLoadingMore}>
                        {isLoadingMore ? (
                            <>
                              <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                              加载中...
                            </>
                        ) : (
                            "加载更多评论"
                        )}
                      </Button>
                    </div>
                )}
              </>
          )}
        </div>

        {/* 删除确认对话框 */}
        <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>确认删除</AlertDialogTitle>
              <AlertDialogDescription>
                {deleteTarget?.type === "comment"
                    ? "确定要删除这条评论吗？删除后将无法恢复，该评论下的所有回复也将被删除。"
                    : "确定要删除这条回复吗？删除后将无法恢复。"}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel disabled={isDeleting}>取消</AlertDialogCancel>
              <AlertDialogAction onClick={handleDelete} disabled={isDeleting} className="bg-red-500 hover:bg-red-600">
                {isDeleting ? (
                    <>
                      <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                      删除中...
                    </>
                ) : (
                    <>
                      <Trash2 className="h-4 w-4 mr-2" />
                      确认删除
                    </>
                )}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
  )
}

